<?php
/**
 * +-------------------------------------------------------------
 * |Caption:
 * +-------------------------------------------------------------
 * |Author: Lenny
 * +-------------------------------------------------------------
 * |Email:  1685964109@qq.com
 * +-------------------------------------------------------------
 * |Date:   2024/6/18 上午9:21
 * +-------------------------------------------------------------
 */

namespace app\common\traits;

use app\Request;
use think\facade\Db;
use think\response\Json;
use app\admin\service\annotation\NodeAnnotation;

trait Curd
{

    /**
     * @NodeAnnotation (title="列表")
     * @return Json
     */
    public function list(): Json
    {
        // 组合查询参数
        list($page, $limit, $where) = $this->buildSearchParams();
        $sql = $this->model;
        if($this->relationSearch){
            // 使用 array_filter 确保 $this->joinTable 是一个非空数组
            $joinTables = array_filter(explode(',', $this->joinTable));
            // 检查是否有多个表需要联查 withJoin 只适用于一对一关系
            if (count($joinTables) > 1) {
                $sql = $sql->withJoin($joinTables,'LEFT');
            } else {
                // 如果只有一个表，直接调用 withJoin
                $sql = $sql->withJoin($this->joinTable,'LEFT');
            }
        }
        $count = $sql->where($where)->count();
        $list  = $sql->where($where)->page($page, $limit)->order($this->sort)->select();
        if ($this->isListEach) $list = $this->format($list);
        return $this->successJson(compact('count','list'));
    }

    /**
     * 组装数据
     */
    public function format($list)
    {

    }

    /**
     * @NodeAnnotation (title="新增")
     * @param Request $request
     * @return Json
     */
    public function add(Request $request): Json
    {
        if(!$request->isPost()) return $this->errorJson('当前请求不合法！');
        $post = $request->post();
        if(!$this->sceneValidate($post, 'add')) return $this->errorJson($this->msg);
        try {
            Db::transaction(function () use ($post)
            {
                $this->model->save($post);
                // 如果有需要添加的关联表数据
                if($this->joinAddTable){
                    foreach(explode(',',$this->joinAddTable) as $table){
                        $localKey      = $this->model->$table()->getLocalKey();
                        $foreignKey    = $this->model->$table()->getForeignKey();
                        // 存在反向关联模型
                        $relationField = $localKey === 'id' ? [$foreignKey => $this->model->id] : [$localKey => $this->model->id];
                        // 关联模型字段格式化
                        $tableField    = json_decode($post[$table], true);

                        // 匹配数据格式
                        if(count($tableField, COUNT_RECURSIVE) === count($tableField)){
                            $tableField = array_merge($tableField, $relationField);
                            $this->model->$table()->save($tableField);
                        }else{
                             array_map(function($item) use ($relationField,$table) {
                                $this->model->$table()->save(array_merge($item, $relationField));
                            }, $tableField);
                        }
                    }
                }
            });
        } catch(\Exception $e) {
            return $this->errorJson('新增失败:' . $e->getMessage());
        }
        return $this->successJson('新增成功');
    }

    /**
     * @NodeAnnotation (title="编辑")
     * @param Request $request
     * @param int     $id
     * @return Json
     */
    public function edit(Request $request, int $id = 0): Json
    {
        if(!$request->isPost()) return $this->errorJson('当前请求不合法！');
        $row = $this->model->find($id);
        if(!$row) return $this->errorJson('数据不存在');
        $post = $request->post();
        try {
            Db::transaction(function () use ($post, $row) {
                $row->save($post);
                if($this->joinUpdateTable){
                    foreach(explode(',',$this->joinUpdateTable) as $table){
                        $localKey      = $row->$table()->getLocalKey();
                        $foreignKey    = $row->$table()->getForeignKey();
                        // 存在反向关联模型
                        $relationField = $localKey === 'id' ? [$foreignKey => $row->id] : [$localKey => $row->id];
                        $tableField    = json_decode($post[$table], true);
                        // 匹配数据格式
                        if(count($tableField, COUNT_RECURSIVE) === count($tableField)){
                            // 查询是否存在
                            if(isset($tableField['id']) && $tableField['id']){
                                $updateTable = $row->$table()->find($tableField['id']);
                                if($updateTable) $save2 = $updateTable->save($tableField);
                            }else{
                                 $row->$table()->save(array_merge($tableField, $relationField));
                            }
                        }else{
                            array_map(function($item) use ($relationField,$row,$table) {
                                if(isset($item['id']) && $item['id']){
                                    $updateTable = $row->$table()->find($item['id']);
                                    if($updateTable) $updateTable->save($item);
                                }else{
                                    $row->$table()->save(array_merge($item, $relationField));
                                }
                            }, $tableField);
                        }
                    }
                }
            });
        }catch (\Exception $e) {
            return $this->errorJson('保存失败:'.$e->getMessage());
        }
        return $this->successJson('保存成功');
    }

    /**
     * @NodeAnnotation (title="字段修改")
     * @param Request $request
     * @return Json
     */
    public function modify(Request $request): Json
    {
        if(!$request->isPost()) return $this->errorJson('当前请求不合法！');
        $post = $request->post();
        $row = $this->model->find($post['id']);
        if(!$row) return $this->errorJson('数据不存在');
        if(!$this->sceneValidate($post, 'modify')) return $this->errorJson($this->msg);
        try {
            Db::transaction(function () use ($post, $row) {
                $row->save([
                                   $post['field'] => $post['value'],
                           ]);
            });
        }catch (\Exception $e) {
            return $this->errorJson($e->getMessage());
        }
        return $this->successJson('操作成功');
    }

    /**
     * @NodeAnnotation (title="删除")
     * @param Request $request
     * @param         $id
     * @return Json
     */
    public function delete(Request $request,$id): Json
    {
        if(!$request->isPost()) return $this->errorJson('当前请求不合法！');
        $ids = explode(',', $id);
        try {
            foreach($ids as $v){
                $sql = $this->model;
                if($this->joinDelTable){
                    // 关联删除
                    $sql  = $sql->with(explode(',',$this->joinDelTable))->find($v);
                    $save = $sql->together(explode(',',$this->joinDelTable))->delete();
                }else{
                    $sql  = $sql->find($v);
                    $save = $sql->delete();
                }
            }
        }catch (\Exception $e) {
            return $this->errorJson('删除失败:'.$e->getMessage());
        }
        if(!$save) return $this->errorJson('删除失败');
        return $this->successJson('删除成功');
    }


}